// Created by lorin
// 2024/07/18 5:35 PM

using System;
using System.IO;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Build;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace Editor
{
    public static class MenuTools
    {
        [MenuItem("Menu Tools/Open Persistent Data Path")]
        private static void OpenDataPath()
        {
            // 获取到 Application.persistentDataPath 的路径
            string path = Application.persistentDataPath;
            // 打开这个路径
            // 注意：在 Windows 上使用 explorer，在 macOS 上使用 open
            System.Diagnostics.Process.Start(path);
        }

        [MenuItem("Menu Tools/Build/New Bundle")]
        private static void BuildNewAssetBundle()
        {
            ClearOldRemoteFile();
            AddressableAssetSettings.BuildPlayerContent(out AddressablesPlayerBuildResult result);
            CopyRemoteFile();
            var apkPath = $"{Environment.CurrentDirectory}/Output/MainApp.apk";
            BuildOptions buildOptions = BuildOptions.None;
            // buildOptions |= 
            BuildPipeline.BuildPlayer(EditorBuildSettings.scenes, apkPath, BuildTarget.Android, buildOptions);
        }
        
        [MenuItem("Menu Tools/Build/Update Bundle")]
        private static void UpdateAssetBundle()
        {
            AddressableAssetSettings.BuildPlayerContent(out AddressablesPlayerBuildResult result);
            Debug.Log($"--->>> OutputPath:{result.OutputPath}");
        }


        private static void ClearOldRemoteFile()
        {
            var sourcePath = $"{Environment.CurrentDirectory}/ServerData/{EditorUserBuildSettings.activeBuildTarget}";
            // var targetPath = $"{Application.streamingAssetsPath}/{EditorUserBuildSettings.activeBuildTarget}";
            var targetPath = $"{Environment.CurrentDirectory}/{Addressables.RuntimePath}/{EditorUserBuildSettings.activeBuildTarget}";
            if (Directory.Exists(sourcePath)) Directory.Delete(sourcePath, true);
            if (Directory.Exists(targetPath)) Directory.Delete(targetPath, true);
        }
        
        private static void CopyRemoteFile()
        {
            var sourcePath = $"{Environment.CurrentDirectory}/ServerData/{EditorUserBuildSettings.activeBuildTarget}";
            // var targetPath = $"{Application.streamingAssetsPath}/{EditorUserBuildSettings.activeBuildTarget}";
            var targetPath = $"{Environment.CurrentDirectory}/{Addressables.RuntimePath}/{EditorUserBuildSettings.activeBuildTarget}";
            bool result = CopyDirectory(sourcePath, targetPath, true, ".bundle");
            Debug.Log($"--->>> 文件复制成功:{result}");
        }
        
        
        /// <summary>
        /// 文件夹下所有内容copy
        /// </summary>
        /// <param name="SourcePath">要Copy的文件夹</param>
        /// <param name="DestinationPath">要复制到哪个地方</param>
        /// <param name="overwriteexisting">是否覆盖</param>
        /// <param name="filter">文件类型</param>
        /// <returns></returns>
        private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting, string filter)
        {
            bool ret = false;
            try
            {
                SourcePath = (SourcePath.EndsWith(@"\") || SourcePath.EndsWith(@"/")) ? SourcePath : SourcePath + @"/";
                DestinationPath = (DestinationPath.EndsWith(@"\") || DestinationPath.EndsWith(@"/")) ? DestinationPath : DestinationPath + @"/";

                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false)
                        Directory.CreateDirectory(DestinationPath);

                    foreach (string fls in Directory.GetFiles(SourcePath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        if (!flinfo.FullName.EndsWith(filter))
                            continue;
                        flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
                    }

                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting, filter) == false)
                            ret = false;
                    }
                }

                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }

            return ret;
        }
    }
}